<template>
  <div class="system-scope-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
      <el-form ref="scopeDialogFormRef" :model="state.ruleForm" size="default" label-width="120px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="作用域名称" prop="scopeName" :rules="[{ required: true, message: '请输入作用域名称', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.scopeName" placeholder="请输入作用域名称" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
        <el-form-item label="显示名称" prop="displayName" :rules="[{ required: true, message: '请输入显示名称', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.displayName" placeholder="请输入显示名称" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
        <el-form-item label="是否默认" prop="isDefault">
          <el-switch v-model="state.ruleForm.isDefault" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="状态">
              <el-switch v-model="state.ruleForm.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="声明列表" prop="claims">
              <div class="claims-container">
                <div v-for="(claim, index) in state.ruleForm.claims" :key="index" class="claim-item">
                  <el-input v-model="state.ruleForm.claims[index]" placeholder="请输入声明名称" class="claim-input">
                    <template #append>
                      <el-button @click="removeClaim(index)" type="danger" :icon="Delete">删除</el-button>
                    </template>
                  </el-input>
                </div>
                <el-button @click="addClaim" type="primary" :icon="Plus" class="mt10">添加声明</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="角色映射">
              <div class="mapping-container">
                <div class="mapping-header">
                  <span>角色</span>
                  <span>对应声明</span>
                  <span>操作</span>
                </div>
                <div v-for="(mapping, role) in state.ruleForm.roleMapping" :key="role" class="mapping-item">
                  <el-input v-model="state.roleMappingKeys[role]" placeholder="角色名称" class="mapping-key" @blur="updateRoleMapping(role)"></el-input>
                  <el-select v-model="state.ruleForm.roleMapping[role]" multiple placeholder="选择声明" class="mapping-value">
                    <el-option v-for="claim in state.ruleForm.claims" :key="claim" :label="claim" :value="claim"></el-option>
                  </el-select>
                  <el-button @click="removeRoleMapping(role)" type="danger" :icon="Delete">删除</el-button>
                </div>
                <el-button @click="addRoleMapping" type="primary" :icon="Plus" class="mt10">添加角色映射</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="权限映射">
              <div class="mapping-container">
                <div class="mapping-header">
                  <span>权限</span>
                  <span>对应声明</span>
                  <span>操作</span>
                </div>
                <div v-for="(mapping, permission) in state.ruleForm.permissionMapping" :key="permission" class="mapping-item">
                  <el-input v-model="state.permissionMappingKeys[permission]" placeholder="权限名称" class="mapping-key" @blur="updatePermissionMapping(permission)"></el-input>
                  <el-select v-model="state.ruleForm.permissionMapping[permission]" placeholder="选择声明" class="mapping-value">
                    <el-option v-for="claim in state.ruleForm.claims" :key="claim" :label="claim" :value="claim"></el-option>
                  </el-select>
                  <el-button @click="removePermissionMapping(permission)" type="danger" :icon="Delete">删除</el-button>
                </div>
                <el-button @click="addPermissionMapping" type="primary" :icon="Plus" class="mt10">添加权限映射</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="描述">
              <el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入作用域描述" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemScopeDialog">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { createScope, updateScope } from '/@/api/oidc/scopes';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const scopeDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    scopeName: '',
    displayName: '',
    description: '',
    isDefault: false,
    claims: [''],
    roleMapping: {},
    permissionMapping: {},
    status: 1,
  },
  roleMappingKeys: {},
  permissionMappingKeys: {},
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});

// 添加声明
const addClaim = () => {
  state.ruleForm.claims.push('');
};

// 删除声明
const removeClaim = (index: number) => {
  if (state.ruleForm.claims.length > 1) {
    state.ruleForm.claims.splice(index, 1);
  }
};

// 添加角色映射
const addRoleMapping = () => {
  const newKey = `role_${Date.now()}`;
  state.ruleForm.roleMapping[newKey] = [];
  state.roleMappingKeys[newKey] = '';
};

// 删除角色映射
const removeRoleMapping = (role: string) => {
  delete state.ruleForm.roleMapping[role];
  delete state.roleMappingKeys[role];
};

// 更新角色映射键
const updateRoleMapping = (oldKey: string) => {
  const newKey = state.roleMappingKeys[oldKey];
  if (newKey && newKey !== oldKey) {
    state.ruleForm.roleMapping[newKey] = state.ruleForm.roleMapping[oldKey];
    delete state.ruleForm.roleMapping[oldKey];
    state.roleMappingKeys[newKey] = newKey;
    delete state.roleMappingKeys[oldKey];
  }
};

// 添加权限映射
const addPermissionMapping = () => {
  const newKey = `permission_${Date.now()}`;
  state.ruleForm.permissionMapping[newKey] = '';
  state.permissionMappingKeys[newKey] = '';
};

// 删除权限映射
const removePermissionMapping = (permission: string) => {
  delete state.ruleForm.permissionMapping[permission];
  delete state.permissionMappingKeys[permission];
};

// 更新权限映射键
const updatePermissionMapping = (oldKey: string) => {
  const newKey = state.permissionMappingKeys[oldKey];
  if (newKey && newKey !== oldKey) {
    state.ruleForm.permissionMapping[newKey] = state.ruleForm.permissionMapping[oldKey];
    delete state.ruleForm.permissionMapping[oldKey];
    state.permissionMappingKeys[newKey] = newKey;
    delete state.permissionMappingKeys[oldKey];
  }
};

// 打开弹窗
const openDialog = (row?: any) => {
  if (row) {
    state.ruleForm = { ...row };
    // 初始化映射键
    state.roleMappingKeys = {};
    Object.keys(row.roleMapping || {}).forEach(key => {
      state.roleMappingKeys[key] = key;
    });
    state.permissionMappingKeys = {};
    Object.keys(row.permissionMapping || {}).forEach(key => {
      state.permissionMappingKeys[key] = key;
    });
    state.dialog.type = 'edit';
    state.dialog.title = '修改作用域';
    state.dialog.submitTxt = '修 改';
  } else {
    state.ruleForm = {
      scopeName: '',
      displayName: '',
      description: '',
      isDefault: false,
      claims: [''],
      roleMapping: {},
      permissionMapping: {},
      status: 1,
    };
    state.roleMappingKeys = {};
    state.permissionMappingKeys = {};
    state.dialog.type = 'add';
    state.dialog.title = '新增作用域';
    state.dialog.submitTxt = '新 增';
  }
  state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = () => {
  scopeDialogFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    
    // 过滤空的声明
    state.ruleForm.claims = state.ruleForm.claims.filter(claim => claim.trim() !== '');
    
    try {
      if (state.dialog.type === 'add') {
        await createScope(state.ruleForm);
        ElMessage.success('新增成功');
      } else {
        await updateScope(state.ruleForm.id, state.ruleForm);
        ElMessage.success('修改成功');
      }
      closeDialog();
      emit('refresh');
    } catch (error) {
      console.error('操作失败:', error);
    }
  });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.claims-container {
  .claim-item {
    margin-bottom: 10px;
    .claim-input {
      width: 100%;
    }
  }
}

.mapping-container {
  .mapping-header {
    display: grid;
    grid-template-columns: 1fr 2fr 100px;
    gap: 10px;
    margin-bottom: 10px;
    font-weight: bold;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .mapping-item {
    display: grid;
    grid-template-columns: 1fr 2fr 100px;
    gap: 10px;
    margin-bottom: 10px;
    align-items: center;
    
    .mapping-key,
    .mapping-value {
      width: 100%;
    }
  }
}
</style>